package com.yangli.leecode.a;

/**
 * @author ly
 * @description #https://leetcode-cn.com/problems/longest-palindromic-substring/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-bao-gu/
 * 最长回形字符串
 * @data 2022/4/21
 */
public class LongestPalindrome {

    public static void main(String[] args) {
        LongestPalindrome longestPalindrome = new LongestPalindrome();
        System.out.println(longestPalindrome.longestPalindrome2("bb"));
    }

    public boolean isPalindromic(String s) {
        int len = s.length();
        for (int i = 0; i < len / 2; i++) {
            if (s.charAt(i) != s.charAt(len - i - 1)) {
                return false;
            }
        }
        return true;
    }

    // 暴力解法
    public String longestPalindrome(String s) {
        String ans = "";
        int max = 0;
        int len = s.length();
        for (int i = 0; i < len; i++)
            for (int j = i + 1; j <= len; j++) {
                String test = s.substring(i, j);
                if (isPalindromic(test) && test.length() > max) {
                    ans = s.substring(i, j);
                    max = Math.max(max, ans.length());
                }
            }
        return ans;
    }


    // 动态规划 d[i][j] = d[i+1][j-1]
    public String longestPalindrome2(String s) {
        int length = s.length();

        if (length < 2) {
            return s;
        }
        boolean[][] subString = new boolean[length][length]; //表示 i,j的字串位置是否是回串
        char[] chars = s.toCharArray();
        String longestPalindrome = s.substring(0, 1);
        for (int i = 0; i < length; ++i) {
            subString[i][i] = true;
        }
        for (int L = 2; L <= length; ++L) { //表示字符串长度，用来计算j的位置
            for (int i = 0; i < length; ++i) {
                int j = L + i - 1;
                if (j >= length) {
                    break;
                }
                if (chars[i] != chars[j]) {
                    subString[i][j] = false;
                } else {
                    if (j - i < 3) { //说明三个字符串以内，肯定是回串
                        subString[i][j] = true;
                    } else {
                        subString[i][j] = subString[i + 1][j - 1];
                    }
                }
                if (subString[i][j] && j - i + 1 > longestPalindrome.length()) {
                    longestPalindrome = s.substring(i, j + 1);
                }
            }
        }
        return longestPalindrome;
    }
}
